package com.xqq.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class GeoJsonGenerator {

    public static void main(String[] args) {
        String csvFilePath = "F:\\我的星网\\项目相关\\缅甸\\2024-11-06-poristion.csv";
        List<List<Double>> coordinates = readCoordinatesFromCsv(csvFilePath);

        // 创建 GeoJSON 字符串
        String geoJson = createGeoJson(coordinates);
//        System.out.println(geoJson);
        // 将 GeoJSON 写入文件
        try (FileWriter file = new FileWriter("trajectory.geojson")) {
            file.write(geoJson);
            System.out.println("GeoJSON 文件已生成：trajectory.geojson");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static List<List<Double>> readCoordinatesFromCsv(String filePath) {
        List<List<Double>> coordinates = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                line = line.substring(1, line.length() - 1);
                String[] parts = line.split(",");
                if (parts.length == 2) {
                    double lon = Double.parseDouble(parts[0]);
                    double lat = Double.parseDouble(parts[1]);
                    List<Double> point = new ArrayList<>();
                    point.add(lon);
                    point.add(lat);
                    coordinates.add(point);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return coordinates;
    }

    private static String createGeoJson(List<List<Double>> coordinates) {
        StringBuilder geoJsonBuilder = new StringBuilder();
        geoJsonBuilder.append("{\n");
        geoJsonBuilder.append("  \"type\": \"FeatureCollection\",\n");
        geoJsonBuilder.append("  \"features\": [\n");

        for (int i = 0; i < coordinates.size(); i++) {
            List<Double> point = coordinates.get(i);
            geoJsonBuilder.append("    {\n");
            geoJsonBuilder.append("      \"type\": \"Feature\",\n");
            geoJsonBuilder.append("      \"geometry\": {\n");
            geoJsonBuilder.append("        \"type\": \"Point\",\n");
            geoJsonBuilder.append("        \"coordinates\": [" + point.get(0) + ", " + point.get(1) + "]\n");
            geoJsonBuilder.append("      },\n");
            geoJsonBuilder.append("      \"properties\": {}\n");
            geoJsonBuilder.append("    }");
            if (i < coordinates.size() - 1) {
                geoJsonBuilder.append(",\n");
            }
        }

        geoJsonBuilder.append("\n  ]\n");
        geoJsonBuilder.append("}\n");

        return geoJsonBuilder.toString();
    }
}